#coding=utf-8
# #######################################
# id : easyXml
# summary : 简易xml内容拾取工具（仅支持UTF-8编码，list方法注意末尾需斜杠）
#           obj = easyXml.parseString('<t><a a1="a11" a2="a22">AAAA</a><b>BBBB</b></t>')
#           attrib = obj.get('/t/a') # {'a1' : 'a11', 'a2' : 'a22'}
#           text = obj.list('/t/') #{'a' : 'AAA', 'b' : 'BBBB'}
# author : yoft <yoft@163.com>
# date : 2011-08-14
# version : 0.0.1
# history :
# #######################################

from xml.etree import ElementTree

class EasyXML:
    def __init__(self):
        self._attrib = {}
        self._data = {}

    def get(self, path, df = ''):
        return self._attrib.get(path, df)

    def list(self, path):
        pos = len(path)
        return dict([(i[pos:], self._data[i]) for i in self._data if i.find(path) == 0])

    def loadFile(self, filename):
        f = open(filename, 'r')
        s = f.read()
        f.close()
        return self.loadString(s)

    def loadString(self, string):
        tree = ElementTree.fromstring(string)
        self.__xml2dict_('/', tree)
        return self

    def __xml2dict_(self, path, tree):
        if tree.attrib:
            self._attrib.update({path + tree.tag : tree.attrib})
        children = tree.getchildren()
        if children:
            for child in children:
                self.__xml2dict_(path + tree.tag + '/', child)
        else:
            self._data.update({path + tree.tag : tree.text})

def parseFile(filename):
    _obj = EasyXML()
    return _obj.loadFile(filename)

def parseString(string):
    _obj = EasyXML()
    return _obj.loadString(string)